package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.AccountBean
import com.glory.cqaospda.bean.LotInfoBean
import com.glory.cqaospda.utils.ByteArrayChange
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.ShiftchangeModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import kotlinx.android.synthetic.main.activity_shiftchange.*
import kotlinx.android.synthetic.main.activity_title.*
import java.lang.Exception

class ShiftchangeActivity : BaseActivity<ShiftchangeModel>() {
    var userName = ""
    var mNfcAdapter: NfcAdapter? = null
    var mPendingIntent: PendingIntent? = null
    lateinit var mFilters: Array<IntentFilter>
    lateinit var mTechLists: Array<Array<String>>
    var lotBean : LotInfoBean? = null
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@ShiftchangeActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }
    override fun initData() {

        queryLotData(etLotId)
        viewModel.defUI.callObserve.observe(this) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("交接班成功", true)
                        finish()
                    }
                    2 -> {

                        val map = JsonObject()
                        map.addProperty("EquipmentName", etEqpId.text.toString())
                        map.addProperty("LotNo", etLotId.text.toString())
                        map.addProperty("ActualOutput", if (etActualOutput.text.toString()=="")"0" else etActualOutput.text.toString())
                        map.addProperty("ShiftOutput", if (etShiftOutput.text.toString()=="")"0" else etShiftOutput.text.toString())
                        map.addProperty("FormMan", Constant.UserName)
                        map.addProperty("ToMan", etWorkCard.text.toString())
                        viewModel.defaultEqpStatusChange(map)
                    }
                    3 -> {
                        val lotsBean = it.item as LotInfoBean
                        lotBean = lotsBean
                    }
                    4 ->{
                        val accountBean = it.item as AccountBean
                        intent.putExtra("type", "Shiftchange")
                        intent.putExtra("name", accountBean.username)
                        intent.putExtra("pass", accountBean.password)
                        intent.setClass(this, SkipDialogActivity::class.java)
                        startActivityForResult(intent, 1)
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

    }

    override fun initView(savedInstanceState: Bundle?) {

        tvTitle.text = "交接班"
        tvUserName.text = Constant.UserName
        tvBaseSubmit.visibility = View.GONE
        FreeApi_ActivityManager.getActivityManager().addActivity(this)
        val instance = MyApp.instance
        instance!!.handler = handler

        checkNFCFunction()
        mPendingIntent = PendingIntent.getActivity(
            this, 0, Intent(
                this,
                javaClass
            ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
        // Setup an intent filter for all MIME based dispatches
        val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        try {
            ndef.addDataType("*/*")
        } catch (e: IntentFilter.MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        mFilters = arrayOf(ndef)

        // 根据标签类型设置
        mTechLists = arrayOf(arrayOf(NfcA::class.java.name))

        etActualOutput.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val actualOutput = if (editable.toString() == "")0 else editable.toString().toInt()
                if(lotBean != null){
                    val lotqty = if(lotBean!!.mLotQty == "")0 else lotBean!!.mLotQty.toInt()
                    if (actualOutput > lotqty){
                        etActualOutput.setText(lotqty.toString())
                    }
                }
            }
        })

        etShiftOutput.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val shiftOutput = if (editable.toString() == "")0 else editable.toString().toInt()
                if(lotBean != null) {
                    val lotqty = if(lotBean!!.mLotQty == "")0 else lotBean!!.mLotQty.toInt()
                    if (shiftOutput > lotqty) {
                        etShiftOutput.setText(lotqty.toString())
                    }
                }
            }
        })

        btnShiftChange.setOnClickListener {
            if (Constant.isFastClick()) {
                if (etWorkCard.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入工卡号", false)
                    return@setOnClickListener
                }
                if (lotBean == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描Lot信息", false)
                    return@setOnClickListener
                }
                if (etActualOutput.text.toString() > lotBean!!.mLotQty) {
                    viewModel.defUI.toastEvent.value =
                        ToastMessageBean("实际产量大于批次产量，当前批次产量为" + lotBean!!.mLotQty, false)
                    return@setOnClickListener
                }
                if (etShiftOutput.text.toString() > lotBean!!.mLotQty) {
                    viewModel.defUI.toastEvent.value =
                        ToastMessageBean("交接班产量大于批次产量，当前批次产量为" + lotBean!!.mLotQty, false)
                    return@setOnClickListener
                }

                val map = JsonObject()
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("LotNo", etLotId.text.toString())
                map.addProperty("ActualOutput", if (etActualOutput.text.toString()=="")"0" else etActualOutput.text.toString())
                map.addProperty("ShiftOutput", if (etShiftOutput.text.toString()=="")"0" else etShiftOutput.text.toString())
                map.addProperty("FormMan", Constant.UserName)
                map.addProperty("ToMan", etWorkCard.text.toString())
                viewModel.defaultEqpStatusChange(map)

//                intent.putExtra("type", "Shiftchange")
//                intent.setClass(this, SkipDialogActivity::class.java)
//                startActivityForResult(intent, 1)
            }
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_shiftchange
    }

    private fun queryLotData(editText: EditText?) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            if (etEqpId.text.toString() == ""){
                viewModel.defUI.toastEvent.value = ToastMessageBean("设备ID不能为空",false)
                return@setEditTextListener
            }
            viewModel.defaultLotInfo(s!!,etEqpId.text.toString())
        }

    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        FreeApi_LogUtils.saveErrorMessages("requestCode="+requestCode+",resultCode="+resultCode,"NFC回传")
        if (requestCode == 1) {
            when (resultCode) {
                1 -> {
                    val extras = data!!.extras
                    userName = extras!!.getString("name").toString()
                    val pass = extras.getString("pass").toString()

                    if ("" == userName) {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("请输入交接班账号", false)
                        return
                    }
                    if ("" == pass) {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("密码未输入", false)
                        return
                    }

                    viewModel.getLoginData(userName, pass)
                }
                2 ->{
                    val extras = data!!.extras
                    val name = extras!!.getString("name").toString()
                    val pass = extras.getString("pass").toString()
                    intent.putExtra("type", "Shiftchange")
                    intent.putExtra("name", name)
                    intent.putExtra("pass", pass)
                    intent.setClass(this, SkipDialogActivity::class.java)
                    startActivityForResult(intent, 1)
                }
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520){
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etLotId -> {
                        etLotId.setText("")
                    }
                }
            }catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onResume() {
        super.onResume()
        enableForegroundDispatch()
    }

    private fun enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter!!.enableForegroundDispatch(
                this, mPendingIntent,
                mFilters, mTechLists
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent)
        val intentActionStr = intent.action // 获取到本次启动的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TECH_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TAG_DISCOVERED == intentActionStr) { // 未知类型
            // 在intent中读取Tag id
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val bytesId = tag!!.id // 获取id数组
            val cardid = ByteArrayChange.ByteArrayToHexString(bytesId).toString()
            if (cardid == "") {
                viewModel.defUI.toastEvent.value = ToastMessageBean("未读取到信息", false)
            } else {
                etWorkCard.setText(ByteArrayChange.ByteArrayToHexString(bytesId))
            }
        }
    }

    private fun checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
        // check the NFC adapter first
//        if (mNfcAdapter == null) {
//
//            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "该设备未发现NFC功能", {
//
//            }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
//
//            return
//        } else {
//            if (!mNfcAdapter!!.isEnabled) {
//
//                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "NFC未开启,是否去开启？", {
//
//                    val setnfc = Intent(
//                        Settings.ACTION_NFC_SETTINGS
//                    )
//                    startActivity(setnfc)
//
//                }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
//                return
//            }
//        }
    }
}